import grok
import megrok.menu
from js.jquery_qtip import qtip
from zope.browsermenu.interfaces import IBrowserMenu
from zope.browserpage import ViewPageTemplateFile
from zope.component import getUtility
from zope.formlib.widget import SimpleInputWidget
import zope.interface
import urllib2

from LCAClassifier.web import resource, interfaces
from LCAClassifier.web.job import LCAClassifyJob


class LCAClassifier(grok.Application, grok.Container):
    pass


class Master(grok.View):
    # Macropage
    grok.context(zope.interface.Interface)

#
# Viewlets
#

class MenuManager(grok.ViewletManager):
    grok.name('menues')
    grok.context(zope.interface.Interface)


class MainMenu(grok.Viewlet):
    grok.viewletmanager(MenuManager)
    grok.name('mainmenu')
    grok.context(zope.interface.Interface)

    def render(self):
        tabs = getUtility(IBrowserMenu, 'tabs')
        html = '<ul>'
        for tab in tabs.getMenuItems(grok.getSite(), self.request):
            html += '<li'
            if tab['selected']:
                html += ' id="current"'
            html += ('><a href="%s">%s</a></li>'
                    % (grok.url(self.request, grok.getSite(), tab['action']),
                       tab['title']))
        html += '</ul>'
        return html


class Tabs(megrok.menu.Menu):
    grok.name('tabs')


class Index(grok.View):
    grok.title('Home')
    megrok.menu.menuitem('tabs', order=1)

    def update(self):
        resource.style.need()


class LCAClassify(grok.View):
    grok.title('LCAClassifier')
    megrok.menu.menuitem('tabs', order=2)

    def update(self):
        resource.style.need()
        qtip.need()

    def lca_form(self):
        form = LCAForm(self.context, self.request)
        return form()


class Download(grok.View):
    grok.title('Download')
    megrok.menu.menuitem('tabs', order=3)

    def update(self):
        resource.style.need()


class Contact(grok.View):
    grok.title('Contact')
    megrok.menu.menuitem('tabs', order=4)

    def update(self):
        resource.style.need()


class MultipleFileUploadWidget(SimpleInputWidget):

    pt = ViewPageTemplateFile('app_templates/multiplefileuploadwidget.pt')

    def __call__(self):
        resource.multiplefileupload.need()
        data = self.pt()
        return data
    
    


def validate_form(form, action, data):
    form.validate(action, data)
    messages = []

    if data['bitscore'] < 0 or data['bitscore'] > 100:
        messages.append('Bitscore need to be in the range [0, 100].')

    if data['minscore'] < 0:
        messages.append('Min score need to be a positive number (>0).')

    #if not ('fastafiles' in data.keys() or 'uri' in data.keys()):
     #   messages.append('No FASTA file provided.')

    return messages


class LCAForm(grok.Form):
    
   
    template = grok.PageTemplateFile('app_templates/lcaclassifier_form.pt')
    
    @property
    def form_fields(self):
        fields = grok.AutoFields(interfaces.ILCAClassify)
        if 'urlinput' in self.request.keys():
            fields = fields.omit('fastafiles')
            fields['uri'].content=self.request['urlinput']
            self.applyChanges(fields['uri'])
            #print ("\n\n\n\n\n%s\n\n\n\n\n\n") % fields['uri'].content
            #self.data.fastafiles=self.request['urlinput']
            
        else:
            fields = fields.omit('uri')
            fields['fastafiles'].custom_widget = MultipleFileUploadWidget
        return fields

    def setUpWidgets(self, ignore_request=False):
        
        super(LCAForm, self).setUpWidgets(ignore_request)
        self.widgets['bitscore'].displayWidth = 20
        self.widgets['minscore'].displayWidth = 20
        

    @grok.action('Run LCA Classifier', validator=validate_form)
    def run_lca_classifier(self, **data):
        db_name = data['database']
        bitscore = data['bitscore']
        minscore = data['minscore']
        email = data['email']
        # Need to handle multiple file upload
        
        # Handling input files
        
        # TODO Auto-fill fasta if given as request
        if 'form.fastafiles' in self.request.form.keys():
            fasta_input_files = self.request.form['form.fastafiles']
            if not isinstance(fasta_input_files, list):
                fasta_input_files = [fasta_input_files]

            fasta_files = {}
            for fasta_file in fasta_input_files:
                disposition = fasta_file.headers.get('content-disposition')
                filename = disposition.split(';')[-1].split('"')[1]
                # It is often path information if IE is used. Removing it.
                filename = filename.split('\\')[-1]
                fasta_file.seek(0)
                fasta_files[filename] = fasta_file.read()
                
        else:
            #print("\n\n\n\n\n%s\n%s\n\n\n\n\n\n") % (self, self.data.uri)
            uri = data['uri']
            response = urllib2.urlopen(uri)
            remoteContent = response.read()
            filename = uri.split('/')[-1].split('#')[0].split('?')[0]
            fasta_files={filename:remoteContent}
            print("\n\n%s\n") % filename

        # Starting job(s), saving job and redirect to result page.
        lca_classify_job = LCAClassifyJob(fasta_files, db_name,
                                          bitscore, minscore, email)
        self.context['jobs'][str(lca_classify_job.jobid)] = lca_classify_job
        url = (grok.url(self.request, self.context) +
               '/jobs/%s' % lca_classify_job.jobid)
        self.redirect(url)
